package com.ctsi.uaa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ctsi.core.atomsms.core.AtomSmsTemplate;
import com.ctsi.core.atomsms.entity.SmsMsg;
import com.ctsi.core.common.api.Result;
import com.ctsi.core.common.constant.Oauth2Constant;
import com.ctsi.core.common.exception.MarsException;
import com.ctsi.core.common.util.$;
import com.ctsi.core.common.util.ThrowableUtil;
import com.ctsi.core.redis.core.RedisService;
import com.ctsi.uaa.enums.UaaExceptionEnum;
import com.ctsi.uaa.service.ValidateService;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @version 1.0
 * @author: wang xiao xiang
 * @date: 2021/8/10 11:06
 */
@Slf4j
@Service
@AllArgsConstructor
public class ValidateServiceImpl implements ValidateService {

    private final RedisService redisService;
    private final AtomSmsTemplate smsTemplate;
    

    @Override
    public Result<?> getCode() {
        Map<String, String> data = new HashMap<>(2);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //SpecCaptcha captcha = new SpecCaptcha(120, 40);
        //String text = captcha.text();// 获取运算的结果：5
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        // 获取运算的结果：5
        String text = captcha.text();
        redisService.set(Oauth2Constant.CAPTCHA_KEY + uuid, text, Duration.ofMinutes(30));
        data.put("key", uuid);
        data.put("codeUrl", captcha.toBase64());
        return Result.data(data);
    }

    @Override
    public Result<?> getSmsCode(String mobile) {

//    	String code = "1188";
//        String code = String.valueOf((int)((Math.random()*9+1)*100000));
//        smsUtil.sendMessage(mobile, "您的验证码为"+code+",有效期为5分钟");
        String code = "";
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            code = String.valueOf(secureRandom.nextInt(900000) + 100000);
        } catch (NoSuchAlgorithmException e) {
            log.error(ThrowableUtil.getStackTrace(e));
        }
        SmsMsg smsMsg = new SmsMsg();
        smsMsg.setMobile(mobile);
        smsMsg.setSmsSignatureSign("QM46017088");
        smsMsg.setSmsTemplateSign("MB21596769");
        JSONObject params = new JSONObject();
        params.put("vaildCode",code);
        smsMsg.setParams(params);
        smsTemplate.sendMsg(smsMsg);
        redisService.set(Oauth2Constant.SMS_CODE_KEY + mobile, code, Duration.ofMinutes(5));
        return Result.success("发送成功");
    }

    @Override
    public void check(String key, String code) {
        Object codeFromRedis = redisService.get(Oauth2Constant.CAPTCHA_KEY + key);
        if ($.isBlank(code)) {
            throw new MarsException(UaaExceptionEnum.VERIFICATION_CODE_IS_EMPTY);
        }
        if ($.isNull(codeFromRedis)) {
            throw new MarsException(UaaExceptionEnum.VERIFICATION_CODE_EXPIRED);
        }
        if (!StringUtils.equalsIgnoreCase(code, codeFromRedis.toString())) {
            throw new MarsException(UaaExceptionEnum.VERIFICATION_CODE_ERROR);
        }
        redisService.del(Oauth2Constant.CAPTCHA_KEY + key);
    }

	@Override
	public Result<?> checkSms(String mobile, String code) {
		String codeFromRedis = null;
		try {
			codeFromRedis = redisService.get(Oauth2Constant.SMS_CODE_KEY + mobile).toString();
		} catch (Exception e) {
			throw new UserDeniedAuthorizationException("验证码不存在！");
		}
		
		if (codeFromRedis == null) {
			throw new UserDeniedAuthorizationException("验证码已过期！");
		}
		// 比较输入的验证码是否正确
		if (!StringUtils.equalsIgnoreCase(code, codeFromRedis)) {
			throw new UserDeniedAuthorizationException("验证码不正确！");
		}
		
		redisService.del(Oauth2Constant.SMS_CODE_KEY + mobile);
		
//		User user = userPassWordService.getUserByMobile(mobile);
//		if($.isEmpty(user)) {
//			throw new UserDeniedAuthorizationException("手机号码不存在，请核查！");
//		}else {
//			return Result.data(user.getAccount());
//		}
        return null;
	}
}